package com.taotao.manager.controller;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.taotao.common.bean.PicUploadResult;
import com.taotao.common.util.FtpUtil;
import com.taotao.common.util.IDUtils;
import com.taotao.manager.service.PropertieService;

/**
 * 图片上传
 */
@Controller
@RequestMapping("/pic")
public class PicUploadController {

	private static final Logger LOGGER = LoggerFactory.getLogger(PicUploadController.class);

	@Autowired
	private PropertieService propertieService;
	
	private static final ObjectMapper mapper = new ObjectMapper();

	// 允许上传的格式
	private static final String[] IMAGE_TYPE = new String[] { ".bmp", ".jpg", ".jpeg", ".gif", ".png" };

	/**
	 * 文件的校验除了文件大小、格式的合法性校验之外，可以新增对图片的高和宽的验证 ，ImageFile
	 * <p>Title: upload</p>
	 * <p>Description: </p>
	 * @param uploadFile
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST,produces= MediaType.TEXT_PLAIN_VALUE)
	@ResponseBody
	public String upload(@RequestParam("uploadFile") MultipartFile uploadFile , HttpServletResponse response) throws Exception {

		// 校验图片格式
		boolean isLegal = false;
		for (String type : IMAGE_TYPE) {
			if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
				isLegal = true;
				break;
			} 
		}

		// 封装Result对象，并且将文件的byte数组放置到result对象中
		PicUploadResult fileUploadResult = new PicUploadResult();
		// 状态
		fileUploadResult.setError(isLegal ? 0 : 1);
		//生成一个新的文件名
		//取原始文件名
		String oldName = uploadFile.getOriginalFilename();

		String newName = IDUtils.genImageName();
		newName = newName + oldName.substring(oldName.lastIndexOf("."));
		/*
		 * ftp文件上传
		 */
		String imagePath = getFilePath();
		isLegal = FtpUtil.uploadFile(propertieService.FTP_ADDRESS, propertieService.FTP_PORT, 
				propertieService.FTP_USERNAME, propertieService.FTP_PASSWORD, 
				propertieService.FTP_BASE_PATH, imagePath, newName, uploadFile.getInputStream());
		String filePath = propertieService.FTP_BASE_PATH+imagePath;//ftp绝对路径
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("Pic file upload .[{}] to [{}] .", uploadFile.getOriginalFilename(), filePath);
		}
		
		String imageUrl = propertieService.IMAGE_BASE_URL + imagePath+"/"+newName;
		
		fileUploadResult.setUrl(imageUrl);// 生成图片的绝对引用地址
		fileUploadResult.setError(isLegal ? 0 : 1);//状态
		//将java对象序列化成json对象
		return mapper.writeValueAsString(fileUploadResult);
	}

	private String getFilePath() {
		// yyyy/MM/dd
		return new DateTime().toString("/yyyy/MM/dd");
	}

}
